<?php

namespace app\admin\controller\paotui;

use app\admin\model\paotui\PostDispatch;
use app\admin\model\paotui\PostOrder;
use app\admin\model\paotui\PostSocket;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use Yansongda\Pay\Pay;

/**
 * 快递管理
 *
 * @icon fa fa-circle-o
 */
class Post extends Backend
{
    protected $type = ['1'=>'支付','2'=>'抢单成功','3'=>'取件','4'=>'送达','5'=>'工作人员取件','6'=>'工作人员取件异常'];
    /**
     * Post模型对象
     * @var \app\admin\model\paotui\Post
     */
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\paotui\Post;
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $filter =  $this->request->get('filter','');
        
            $filter = json_decode($filter);
            $poster_id = empty($filter->poster_id)?0:$filter->poster_id;
            unset($filter->poster_id);
            $this->request->get(['filter'=>json_encode($filter)]);

            // $type = $this->request->param('type',1);
            // switch ($type){
            //     case 1:
            //         $_where = ['pay_status'=>1,'type'=>['in','1,2']];
            //         break;
            //     case 2:
            //         $_where = ['pay_status'=>1,'type'=>3];
            //         break;
            // }

            $_where1 = ['post.is_delete'=>0];
            if($poster_id){
                $_where1 = function($query) use ($poster_id){
                   return $query->where("collect_poster_id",$poster_id)
                       ->whereOr('reach_poster_id',$poster_id);
                };
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // p($where);die;
            // p($this->request->request());die;
			$pst=$this->request->request('status');
            if($this->request->request('type')){
                $wherex['type'] = $this->request->request('type');
            // }else{
                // $wherex = $where;
            }
			if($pst){
				if($pst==3){
					$wherex['post.status'] = 5;
				}elseif($pst==4){
					// $wherex['post.status'] = 1;
					$wherex['post.pay_status'] = 0;
				}elseif($pst==5){
					$wherex['post.status'] = -1;
				}
            }
            
            $sort = $sort;
            $total = $this->model
                ->alias('post')
                ->join('pt_user u ','u.id = post.user_id','left')
                ->field('post.*,u.mobile,post.id as id')
                ->where($where)
                ->where($wherex)
                ->where($_where)
                ->where($_where1)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->alias('post')
                ->join('pt_user u ','u.id = post.user_id','left')
                ->field('post.*,u.mobile')
                ->where($where)
                ->where($wherex)
                ->where($_where)
                ->where($_where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

            foreach ($list as $k=>&$v){
                $v['u.mobile'] = $v['mobile'];
                if($v['poster_id']){
                    $posterModel = new \app\admin\model\paotui\Poster();
                    $posterInfo = $posterModel->where(['id'=>$v['poster_id']])->find();
                    if(!empty($posterInfo)){
                        $v['poster_name'] = $posterInfo['poster_name']."【". $posterInfo['mobile']."】";
                    }
                }else{
                    $v['poster_name']="";
                }

                if($poster_id){
                    if($v['collect_poster_id'] != $v['reach_poster_id']){
                        $brokerage = [$v['collect_poster_id']=>$v['collect_brokerage'],$v['reach_poster_id']=>$v['reach_brokerage']];
                        $v['brokerage'] = $brokerage[$poster_id];

                        if($v['collect_poster_id'] == $poster_id){
                            $poster_type = "揽收";
                        }else if($v['reach_poster_id'] == $poster_id){
                            $poster_type = "派送";
                        }

                        $v['poster_type'] = $poster_type;
                    }else{
                        $v['poster_type'] = "独立";
                    }
                }
                //2023.10.13
                if($v['type'] == 2){
                    //发件 从驿站发出
                    $station = Db::name('station')->where(['id'=>$v['from_address_id']])->find();
                    $school = Db::name('school')->where(['id'=>$station['school']])->find();
                    $v['from_district'] = $school['name'];
                    $v['from_poi'] = $station['name'];
                    $v['from_address'] = $station['address'];
                    $v['from_name'] = '';
                    $v['from_mobile'] = '';
                    
                    //收件 用户
                    $userschool = Db::name('user_school')->where(['id'=>$v['to_address_id']])->find();
                    $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                    $v['to_district'] = $school['name'];
                    $v['to_poi'] = $building['name'];
                    $v['to_address'] = $userschool['house_number'];
                    $v['to_name'] = $userschool['nickname'];
                    $v['to_mobile'] = $userschool['phone'];
                }
                if($v['type'] == 4){
                    $userschool = Db::name('user_school')->where(['id'=>$v['user_school_id']])->find();
                    $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
                    $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
                    $v['send_district'] = $school['name'];
                    $v['send_poi'] = $building['name'];
                    $v['send_address'] = $userschool['house_number'];
                    $v['send_name'] = $userschool['nickname'];
                    $v['send_mobile'] = $userschool['phone'];
                   
                }
            }
            // p($list);die;
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 物流跟踪
     */
    public function order(){
        $ids = $this->request->param('ids');

        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $id = $this->request->param('id');
            $model = new PostOrder();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $model
                ->alias('post')
                ->where($where)
                ->where("post_id",$id)
                ->order($sort, $order)
                ->count();

            $list = $model
                ->alias('post')
                ->where($where)
                ->where("post_id",$id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach($list as $k=>$v){
                $list[$k]['type_name'] = $this->type[$v['type']];
                $list[$k]['createtime'] = date("Y-m-d H:i:s",$v['createtime']);
            }

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $this->assign('id',$ids);
        return $this->view->fetch();
    }


    /**
     * 更换骑手
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change_poster($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(!in_array($row['status'],[3,4,5])){
                        $this->error("当前订单的状态已不能指派");
                    }
                    if($row['status'] == 3){
                        $params['collect_poster_id'] = $params['poster_id'];
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster',$posterModel->where(['status'=>1])->select());

        return $this->view->fetch();
    }

    /**
     * 手动指派
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hand_dispatch($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(!in_array($row['status'],[2,8,9])){
                        $this->error("当前订单的状态已不能指派");
                    }

                    $postDispatchModel = new PostDispatch();
                    $postDispatchModel->save(['post_id'=>$row['id'],'poster_id'=>$params['poster_id'],'type'=>2]);

                    //生成socket记录
                    $postSocketModel = new PostSocket();
                    $postSocketInfo = $postSocketModel->where(['post_id'=>$row['id']])->find();
                    if($postSocketInfo){
                        $postSocketInfo->save(['type'=>3,'poster_id'=>$params['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>time(),'send_status'=>0]);
                    }else{
                        $postSocketModel = new PostSocket();
                        $postSocketModel->save(['type'=>3,'post_id'=>$row['id'],'poster_id'=>$params['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>time(),'send_status'=>0]);
                    }

                    $params['status'] = 8;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster',$posterModel->where(['status'=>1])->select());

        return $this->view->fetch();
    }
    //发送未付款短信
    public function send_email($ids = null){
        $row = $this->model->get($ids);
        $user =Db::name('user')->where('id',$row['user_id'])->find();
        
        // 直接发送短信
        $config = get_addon_config('alisms');
        $mobile = $user['mobile'];
        // $mobile = '17798800337';
        $template = $config['template']['orderpay'];
        $sign = '';
        if (!$mobile || !$template) {
            $this->error('手机号、模板ID不能为空');
        }
        $sign = $sign ? $sign : $config['sign'];
        // $param = (array)json_decode($this->request->post('param', '', 'trim'));
            // $param['code'] = '1111';
        $alisms = new \addons\alisms\library\Alisms();
        $ret = $alisms->mobile($mobile)
            ->template($template)
            ->sign($sign)
            // ->param($param)
            ->send();
	    if($ret){
	        $this->success('发送成功');
	    }else{
	        $this->error('发送失败');
	    }
    }
    /**
     * 设置价格
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function price($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(!in_array($row['status'],[0])){
                        $this->error("当前订单的状态不能设置价格");
                    }
    

                    $params['status'] = 1;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        

        return $this->view->fetch();
    }
     /**
     * 取1入库
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function incloth($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['washtype'] = 1;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster',$posterModel->where(['status'=>1])->select());
        $userschool = Db::name('user_school')->where(['id'=>$row['to_address_id']])->find();
        $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
        $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
        $row['from_district'] = $school['name'];
        $row['from_poi'] = $building['name'];
        $row['from_address'] = $userschool['house_number'];
        $row['from_name'] = $userschool['nickname'];
        $row['from_mobile'] = $userschool['phone'];
        $row['typetext'] = '寄快递';
         //跑腿人员
        $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
        $row['poster'] = $poster;
        $log2 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'服务收入'])->find();
    
        $row['fwmoney'] = $log2['money'];  
       
        $this->assign('row',$row);
        return $this->view->fetch();
    }
     /**
     * 出库
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function outcloth($ids = null){
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['washtype'] = 1;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $posterModel = new \app\admin\model\paotui\Poster();
        $this->assign('poster',$posterModel->where(['status'=>1])->select());
        $userschool = Db::name('user_school')->where(['id'=>$row['to_address_id']])->find();
        $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
        $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
        $row['from_district'] = $school['name'];
        $row['from_poi'] = $building['name'];
        $row['from_address'] = $userschool['house_number'];
        $row['from_name'] = $userschool['nickname'];
        $row['from_mobile'] = $userschool['phone'];
        $row['typetext'] = '寄快递';
         //跑腿人员
        $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
        $row['poster'] = $poster;
        $log2 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'服务收入'])->find();
    
        $row['fwmoney'] = $log2['money'];  
       
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function detail($ids = null){
         $row = $this->model->get($ids);
         $codearr = [];
         $row['qjmoney'] =0;
         $row['fwmoney']  = 0;
        
        if($row['poster_id']){
            $posterModel = new \app\admin\model\paotui\Poster();
            $posterInfo = $posterModel->where(['id'=>$row['poster_id']])->find();
            if(!empty($posterInfo)){
                $row['poster_name'] = $posterInfo['poster_name']."【". $posterInfo['mobile']."】";
            }
        }else{
            $row['poster_name']="";
        }
        
        $row['send_district'] = '';
        $row['send_poi'] = '';
        $row['send_address'] = '';
        $row['send_name'] = '';
        $row['send_mobile'] = '';
 //2023.10.13
          $row['poster_name'] = '';
        if($row['type'] == 2){
            //发件 从驿站发出
            $station = Db::name('station')->where(['id'=>$row['from_address_id']])->find();
            $school = Db::name('school')->where(['id'=>$station['school']])->find();
            $row['from_district'] = $school['name'];
            $row['from_poi'] = $station['name'];
            $row['from_address'] = $station['address'];
            $row['from_name'] = '';
            $row['from_mobile'] = '';
            
            //收件 用户
            $userschool = Db::name('user_school')->where(['id'=>$row['to_address_id']])->find();
            $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
            $row['to_district'] = $school['name'];
            $row['to_poi'] = $building['name'];
            $row['to_address'] = $userschool['house_number'];
            $row['to_name'] = $userschool['nickname'];
            $row['to_mobile'] = $userschool['phone'];
            $row['typetext'] = '取快递';
            
            //取件码
            $codes  = Db::name('partition_code')->where(['paotui_post_id'=>$row['id']])->select();
         
            $codearr = [];
            foreach($codes as $k=>&$v){
                //取件码分组
                $partition = Db::name('partition')->where(['id'=>$v['partition_id']])->find();
                
                $station = Db::name('station')->where(['id'=>$partition['station_id']])->find();
                $v['takeuser'] = Db::name('paotui_poster')->where(['id'=>$v['take_user_id']])->find();
                $v['takeuserphone'] =  $v['takeuser']['mobile'];
                $v['takeuser'] = $v['takeuser']['poster_name'];
                
                $data = [
                    'partition_name'=>$partition['name'],
                    'code'=>$v['codes'],
                    'data'=>$v
                ];
                
                $codearr[$station['id']]['data'][] =  $data;
                $codearr[$station['id']]['name'] = $station['name'];
            }
            //跑腿人员
            $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
            $row['poster'] = $poster;
            //佣金
            $log1 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'取件分佣'])->find();
            $row['qjmoney'] = $log1['money'];
            $log2 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'服务收入'])->sum('money');
            $row['fwmoney'] = $log2;
            
        }
        if($row['type'] == 4){
            $userschool = Db::name('user_school')->where(['id'=>$row['from_address_id']])->find();
            $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
            $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
            $row['from_district'] = $school['name'];
            $row['from_poi'] = $building['name'];
            $row['from_address'] = $userschool['house_number'];
            $row['from_name'] = $userschool['nickname'];
            $row['from_mobile'] = $userschool['phone'];
            $row['typetext'] = '寄快递';
             //跑腿人员
            $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
            $row['poster'] = $poster;
             $log2 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'服务收入'])->find();
    
                $row['fwmoney'] = $log2['money'];
            
        }
        if($row['type'] == 5){
            $userschool = Db::name('user_school')->where(['id'=>$row['to_address_id']])->find();
            $school = Db::name('school')->where(['id'=>$userschool['school_id']])->find();
            $building = Db::name('building')->where(['id'=>$userschool['building_id']])->find();
            $row['from_district'] = $school['name'];
            $row['from_poi'] = $building['name'];
            $row['from_address'] = $userschool['house_number'];
            $row['from_name'] = $userschool['nickname'];
            $row['from_mobile'] = $userschool['phone'];
            $row['typetext'] = '寄快递';
             //跑腿人员
            $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
            $row['poster'] = $poster;
             $log2 = Db::name('paotui_poster_money_log')->where(['source_id'=>$row['id'],'memo'=>'服务收入'])->find();
    
                $row['fwmoney'] = $log2['money'];
            
        }
        if($row['type'] == 1){
            $row['typetext'] = '同城跑腿';
            $poster = Db::name('paotui_poster')->where(['id'=>$row['poster_id']])->find();
            $row['poster'] = $poster;
        }
         
        
          
        
        
         
        $this->assign('codearr',$codearr);       
        $this->assign('row',$row);
        return $this->view->fetch();
    }
	
    /**
     * 取消
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function cancel($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->where('status','in',[0,1,2,3,4,5])->select();
        
		$time=time();
		
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count1 = $item->save(['status'=>-1,'canceltime'=>$time]);
				if($count1){
				// 	if($item['pay_price'] >0 ){
				// 		if($item['status'] == 2 || $item['status'] == 3|| $item['status'] == 4){
						    
				// 			//退款,原路退回
				// 			try {
				// 				$config = \addons\epay\library\Service::getConfig('wechat');

				// 				$config['app_id'] = $config['miniapp_id'];
				// 				$pay = Pay::wechat($config);
				// 				$param = [
				// 					'transaction_id'=>$item['transaction_id'],
				// 					'out_refund_no'=>$time."_".rand(1000,9999),
				// 					'total_fee' => $item['pay_price']*100,
				// 					'refund_fee'=> $item['pay_price']*100,
				// 					'refund_desc'=>"退款"
				// 				];

				// 				$result = $pay->refund($param);
				// 				if($result->result_code == "SUCCESS"){

				// 					if($item['status'] == 3){
				// 						//生成socket记录
				// 						$postSocketModel = new PostSocket();
				// 						$postSocketInfo = $postSocketModel->where(['post_id'=>$item['id']])->find();
				// 						if($postSocketInfo){
				// 							$postSocketInfo->save(['type'=>4,'poster_id'=>$item['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>$time,'send_status'=>0]);
				// 						}else{
				// 							$postSocketModel = new PostSocket();
				// 							$postSocketModel->save(['type'=>4,'post_id'=>$item['id'],'poster_id'=>$item['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>$time,'send_status'=>0]);
				// 						}
				// 					}
				// 					Db::commit();
				// 					$count+=$count1;
				// 				}
				// 			}catch (\Yansongda\Pay\Exceptions\Exception $e){
				// 				Db::rollback();
				// 				$this->error("退款申请失败，请联系客服");
				// 			}
				// 		}else{
							
				// 			$pcode = Db::name('partition_code')->where(['paotui_post_id'=>$item['id']])->update(['canceltime'=>$time]);
				// 			Db::commit();
							
				// 			$count+=$count1;
				// 		}
				// 	}else{
						$pcode = Db::name('partition_code')->where(['paotui_post_id'=>$item['id']])->update(['canceltime'=>$time]);
						Db::commit();
						$count+=$count1;
				// 	}
				}
				
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
	
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->where('status',-1)->select();

		$time=time();
		
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->save(['is_delete'=>1,'deletetime'=>$time]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    
    public function tuikuan($ids = null){
        $ids = $ids ?: $this->request->post("ids");
        $pk = $this->model->getPk();
        $item = $this->model->where($pk, 'in', $ids)->find();
        
        $config = \addons\epay\library\Service::getConfig('wechat');

		$config['app_id'] = $config['miniapp_id'];
		$pay = Pay::wechat($config);
		$param = [
			'transaction_id'=>$item['transaction_id'],
			'out_refund_no'=>$time."_".rand(1000,9999),
			'total_fee' => $item['pay_price']*100,
			'refund_fee'=> $item['pay_price']*100,
			'refund_desc'=>"退款"
		];

		$result = $pay->refund($param);
		if($result->result_code == "SUCCESS"){
		    $this->model->where($pk, 'in', $ids)->update(['refund_content'=>'1']);
			if($item['status'] == 3){
				//生成socket记录
				$postSocketModel = new PostSocket();
				$postSocketInfo = $postSocketModel->where(['post_id'=>$item['id']])->find();
				if($postSocketInfo){
					$postSocketInfo->save(['type'=>4,'poster_id'=>$item['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>$time,'send_status'=>0]);
				}else{
					$postSocketModel = new PostSocket();
					$postSocketModel->save(['type'=>4,'post_id'=>$item['id'],'poster_id'=>$item['poster_id'],'distance'=>0,'send_num'=>0,'next_send_time'=>$time,'send_status'=>0]);
				}
			}
			$this->success('退款成功');
		}else{
		    $this->error('退款失败');
		}
    }
}
